# -*- coding: utf-8 -*-
# 创建时间：2021/12/20 14:08
from bs4 import BeautifulSoup
import requests
import time, math, random, json
import pymysql
import re
from xlwt import Workbook
from hhy import FileUtil, DateUtil, ToolUtil, HttpUtil

__author__ = 'LuckyHhy'

def get_content(url):
    headers = {"User-Agent": HttpUtil.AgentRandom()}
    A = requests.session()  # 用一个会话请求
    A.headers = headers
    cont = A.get(url, timeout=20, allow_redirects=False)
    return cont.json()


def getData():
    base_url = "https://geradornv.com.br/wp-json/api/generator-name"
    output = """{}\n"""
    num = 0
    data = []
    while num < 1000:
        num += 1
        result=get_content(base_url)
        data.append(result['fullname'])
        print('获取第_{0}_个名字_{1}'.format(num,result['fullname']))
        save_txt(output.format(result['fullname']))


    save_xls()

def read_txt():
    filename = 'brail_name.txt'  # txt文件和当前脚本在同一目录下，所以不用写具体路径
    data=[]
    with open(filename, 'r', encoding='utf-8') as file_to_read:

        while True:
            lines = file_to_read.readline()  # 整行读取数据
            if not lines:
                break
                pass
            data.append(lines)
    return data



def save_xls(pathh):
    w = Workbook()
    ws = w.add_sheet('datas')  # 创建一个工作表
    results = read_txt()
    i = 0
    g = 0
    for row in results:
        ws.write(i, g, row)  # 行 ，列  数据
        i = i + 1

    print("已经跳出来了")
    w.save(pathh)

# 保存到文本中
def save_txt(*args):
    for i in args:
        with open('brail_name.txt', 'a', encoding='utf-8') as f:
            f.write(i)


def main():
    #爬取事情
    #getData()
    #保存到 xls
    save_xls('lang_name.xls')
    pass


if __name__ == '__main__':
    main()
